package database

import (
	"fmt"
	"log"
	"time"

	"alfred/models"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type DB struct {
	*gorm.DB
}

// NewDB 创建数据库连接
func NewDB(dataSourceName string) (*DB, error) {
	// 使用不依赖CGO的SQLite驱动
	db, err := gorm.Open(sqlite.Open(dataSourceName), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return nil, err
	}

	return &DB{db}, nil
}

// InitTables 初始化数据库表
func (db *DB) InitTables() error {
	// 自动迁移所有模型
	err := db.AutoMigrate(
		&models.Flow{},
		&models.Node{},
		&models.Action{},
		&models.FlowExecution{},
		&models.NodeExecution{},
		&models.ActionExecution{},
		&models.NotificationConfig{},
	)
	if err != nil {
		return fmt.Errorf("failed to migrate tables: %v", err)
	}

	log.Println("Database tables initialized successfully")
	return nil
}

// CreateFlow 创建Flow
func (db *DB) CreateFlow(flow *models.Flow) error {
	flow.ID = models.NewID()
	flow.CreatedAt = time.Now()
	flow.UpdatedAt = time.Now()

	return db.Create(flow).Error
}

// GetFlow 获取Flow
func (db *DB) GetFlow(id string) (*models.Flow, error) {
	var flow models.Flow
	err := db.First(&flow, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &flow, nil
}

// GetFlowByBranch 根据分支获取Flow
func (db *DB) GetFlowByBranch(branch string) (*models.Flow, error) {
	var flow models.Flow
	err := db.First(&flow, "branch = ?", branch).Error
	if err != nil {
		return nil, err
	}
	return &flow, nil
}

// GetFlowByBranchAndRepo 根据分支和仓库URL获取Flow
func (db *DB) GetFlowByBranchAndRepo(branch, repoURL string) (*models.Flow, error) {
	var flow models.Flow
	err := db.First(&flow, "branch = ? AND repo_url = ?", branch, repoURL).Error
	if err != nil {
		return nil, err
	}
	return &flow, nil
}

// ListFlows 获取所有Flow
func (db *DB) ListFlows() ([]*models.Flow, error) {
	var flows []*models.Flow
	err := db.Order("created_at DESC").Find(&flows).Error
	return flows, err
}

// UpdateFlow 更新Flow
func (db *DB) UpdateFlow(flow *models.Flow) error {
	flow.UpdatedAt = time.Now()
	return db.Save(flow).Error
}

// DeleteFlow 删除Flow
func (db *DB) DeleteFlow(id string) error {
	return db.Delete(&models.Flow{}, "id = ?", id).Error
}

// Close 关闭数据库连接 (兼容旧API)
func (db *DB) Close() error {
	sqlDB, err := db.DB.DB()
	if err != nil {
		return err
	}
	return sqlDB.Close()
}
